package com.yingsheng.bi.hks.web.component;

import com.yingsheng.bi.hks.basic.ReqContext;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * Web拦截打印业务名称
 *
 * @author root
 */
@Slf4j
public class HandlerMethodInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            if (handler != null && handler instanceof HandlerMethod) {
                HandlerMethod handlerMethod = (HandlerMethod) handler;
                ApiOperation api = handlerMethod.getMethodAnnotation(ApiOperation.class);
                if (api != null) {
                    log.info("{} Operation: [{}]", request.getRequestURI(), api.value());
                }
            }
        } catch (Throwable t) {
            log.warn(t.getMessage());
        }
        return true;
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        try {
            ReqContext.reset();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

}
